package com.gexiaobao.pigeon.ui.fragment.match

import android.annotation.SuppressLint
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.view.View
import android.webkit.JsResult
import android.webkit.SslErrorHandler
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.model.bean.RaceTypeResponse
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.databinding.FragmentSpecifyInfoBinding
import com.gexiaobao.pigeon.ui.race.RaceViewModel
import me.hgj.jetpackmvvm.ext.nav

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 11:06
 * @Describe    : 指定信息
 */
class FragmentSpecifyInfo : BaseFragment<RaceViewModel, FragmentSpecifyInfoBinding>(){

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.toolbar.initClose("参赛项目信息") {
            nav().navigateUp()
        }
    }

    @SuppressLint("SetJavaScriptEnabled", "JavascriptInterface")
    override fun initData() {
        super.initData()
        val mData = arguments?.getSerializable("data") as RaceTypeResponse.RaceTypeListBean
        val token = KvUtils.decodeString(Constant.TOKEN)

        var str = ""
        when (mData.baseStatus) {
            1 -> {
                str = "未开始"
            }

            2 -> {
                str = "进行中"
            }

            3 -> {
                str = "已结束"
            }
        }

        var webUrl = ""
        if (mData.baseType == 2) {//http://101.200.150.173:9092/   http://10.10.12.226:4210 http://project.gexiaobao.cn
            webUrl = Constant.SPECIFY_URL + "/#/sign/info/" + mData.baseId + "?baseId=" + mData.baseId +
                    "&baseName=" + mData.baseName +
                    "&aboutPassIds=" + mData.aboutPassIds +
                    "&baseStatus=" + mData.baseStatus +
                    "&startTime=" + mData.startTime +
                    "&endTime=" + mData.endTime +
                    "&str=" + str +
                    "&orgId=" +
                    "&baseType=" + mData.baseType +
                    "&token=" + token +
                    "&projectId=" + mData.projectId +
                    "&projectName=" + mData.baseName
        } else {
            webUrl = Constant.SPECIFY_URL + "/#/sign/info/" + mData.baseId + "?baseId=" + mData.baseId +
                    "&baseName=" + mData.baseName +
                    "&aboutPassIds=" + mData.aboutPassIds +
                    "&baseStatus=" + mData.baseStatus +
                    "&startTime=" + mData.startTime +
                    "&endTime=" + mData.endTime +
                    "&str=" + str +
                    "&orgId=" +
                    "&baseType=" + mData.baseType +
                    "&token=" + token
        }
        mDatabind.webviewSpecifyInfo.postDelayed({ mDatabind.webviewSpecifyInfo.loadUrl(webUrl) }, 500)
        val webSettings = mDatabind.webviewSpecifyInfo.settings
        webSettings.javaScriptEnabled = true//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        webSettings.domStorageEnabled = true//DOM Storage
        webSettings.userAgentString = webSettings.userAgentString + "Android-Pigeon"
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE//不使用缓存，只从网络获取数据.
        //支持屏幕缩放
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        //扩大比例的缩放
        webSettings.useWideViewPort = true
        // 自适应屏幕
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.loadWithOverviewMode = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true//设置js可以直接打开窗口，如window.open()，默认为false
        webSettings.setSupportZoom(true)//是否可以缩放，默认true
        webSettings.builtInZoomControls = false//是否显示缩放按钮，默认false
        webSettings.useWideViewPort = true//设置此属性，可任意比例缩放。大视图模式
        webSettings.loadWithOverviewMode = true//和setUseWideViewPort(true)一起解决网页自适应问题
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW//加载https和http混合模式
        mDatabind.webviewSpecifyInfo.addJavascriptInterface(this, "android");//添加js监听 这样html就能调用客户端
        mDatabind.webviewSpecifyInfo.webChromeClient = webChromeClient
        mDatabind.webviewSpecifyInfo.webViewClient = webViewClient
    }

    private val webViewClient: WebViewClient = object : WebViewClient() {

        override fun onPageFinished(view: WebView, url: String) {//页面加载完成

        }

        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
//            Log.i("anSen", "拦截url:$url")
//            if (url == "http://www.google.com/") {
//                return true//表示我已经处理过了
//            }
            view.loadUrl(url)
            return true
        }

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            view?.loadUrl(request?.url.toString())//request.getUrl().getPath()得到的相对路径，加载会失败(出现空白页)
            return true
        }

        override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mDatabind.webviewSpecifyInfo.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }
        }
    }

    private val webChromeClient: WebChromeClient = object : WebChromeClient() {

        override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            return super.onJsAlert(view, url, message, result)
        }

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
        }

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            mDatabind.progressBar.visibility = View.VISIBLE
            mDatabind.progressBar.progress = newProgress
            if (newProgress == 100) {
                mDatabind.progressBar.visibility = View.GONE
            }
        }
    }

    override fun onDestroyView() {
        if (mDatabind.webviewSpecifyInfo != null) {
            mDatabind.webviewSpecifyInfo.clearCache(true)
            mDatabind.webviewSpecifyInfo.clearHistory()
            mDatabind.webviewSpecifyInfo.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            mDatabind.webviewSpecifyInfo.clearHistory()
            mDatabind.webviewSpecifyInfo.destroy()
        }
        super.onDestroyView()
    }
}